package com.changpei.log.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.changpei.common.cache.UserCache;
import com.changpei.log.service.LogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 *
 *
 * @author Way on 2021/9/14
 */
@Service
@Slf4j
public class LogServiceImpl implements LogService {

    @Autowired
    private UserCache userCache;

    @Override
    public void process(Map<String, Object> param) {
        try {
            String str = param.get("cm").toString();
            String token = param.get("token").toString();
            String[] words = str.split("\\|");
            Long userId = userCache.getUserId(token);
            JSONObject jsonObject = JSONObject.parseObject(words[1]);
            jsonObject.put("uid", userId);
            // 记录日志
            log.info(words[0] + "|" + jsonObject.toJSONString());

            // 解析日志
            JSONArray et = jsonObject.getJSONArray("et");
            Set<String> tags = new LinkedHashSet<>();

            for (Object o : et) {
                JSONObject object = JSONObject.parseObject(o.toString());
                // 判断首页刷新是否推荐新数据
                if ("detail".equals(object.getString("en"))) {
                    // 添加用户标签
                    JSONObject kv = object.getJSONObject("kv");
                    if (kv.containsKey("tags")) {
                        JSONArray array = kv.getJSONArray("tags");

                        for (Object tag : array) {
                            tags.add(tag.toString());
                        }
                    }
                }
            }

            if (!tags.isEmpty()) {
                LinkedList<String> strings = new LinkedList<>(tags);
                Collections.reverse(strings);

                System.out.println("用户标签--------->" + strings);
                for (String string : strings) {
                    userCache.addTags(userId, string);
                }
            }
        } catch (Exception e) {
            log.warn("解析日志异常：", e.getMessage());
        }
    }
}
